home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6617 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  61 lines

  1. Newsgroups: comp.lang.c
  2. Path: lafn.org!an234
  3. From: an234@lafn.org (Andres Lessing)
  4. Subject: Re: Arrays of strings
  5. X-Nntp-Posting-Host: lafn.org
  6. Message-ID: <1996Feb17.211357.13063@lafn.org>
  7. Sender: news@lafn.org
  8. Reply-To: an234@lafn.org (Andres Lessing)
  9. Organization: The Los Angeles Free-Net
  10. References: <Pine.SOL.3.91.960207141605.27357A-100000@nova>  
  11. Date: Sat, 17 Feb 1996 21:13:57 GMT
  12.  
  13.  
  14. In a previous article, ldigiova@nova.umuc.edu (Larry DiGiovanni) says:
  15.  
  16. >
  17. >I'm trying to read lines of a text file and load those lines into an 
  18. >array.  I have a couple of questions...
  19. >
  20. >1.  How do I declare the array to contain the text.  When it is declared, 
  21. >I will not know how many lines are in the text file.  char **txtarray?
  22. >
  23. >2.  How do I allocate the space for the data once I know how many lines 
  24. >are in the text file?  txtarray = malloc((size_t)(nelements))?
  25. >
  26. >3.  What is the best way to read from the text file into the array 
  27. >elements? fscanf? fgets?  I have had no success reading directly into the 
  28. >elements with these two functions.  I don't understand why, but it may be 
  29. >related to my poor understanding of (1) and (2) above as well.
  30. >
  31. >Any help would be greatly appreciated.  TIA
  32. >
  33. >Larry DiGiovanni
  34. >
  35. >
  36.  
  37. My best guess would be to crate a structure as follows:
  38.  
  39. #define MAXCHAR   128
  40.  
  41. struct Text{
  42.   char line[MAXCHAR];
  43.   struct Text *next;
  44. }
  45.  
  46. Then read a line and then create another structure using malloc:
  47.  
  48.   (struct Text *)malloc(sizeof(struct Text))
  49.  
  50. then you don't have to worry about how many lines there are... just 
  51. traverse the linked list.  You however could create functions to count 
  52. characters per line or number of lines.
  53.  
  54.  
  55.  
  56. -- 
  57.  Hofstadter's Law:                   |       o__
  58.     It always takes longer than you expect, even   |     _.</)_
  59.     when you take Hofstadter's Law into account.   |    (_) \(_)
  60.         " Godel Escher Bach"               | Andres, an234@lafn.org
  61.